﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace InvasionWars
{
    public class CardReader
    {

        public static List<Card> ReadArmyCards(Armies army)
        {
            List<Card> cards = new List<Card>();
            //xmlreader
            string fileName = "Cards.xml";
            XmlDocument xml = new XmlDocument();
            try
            {
                FileStream file = File.Open(fileName, FileMode.Open, FileAccess.Read);
                xml.Load(file);
                //xml.LoadXml(fileName);

                XmlNodeList cardList;
                if (army == Armies.HUMAN)
                {
                    cardList = xml.SelectNodes("/Cards/Humans/Card");
                }
                else
                {
                    cardList = xml.SelectNodes("/Cards/Aliens/Card");
                }

                foreach (XmlNode aCard in cardList)
                {
                    cards.Add(new Card(aCard.Attributes["id"].Value,
                                        aCard.Attributes["name"].Value,
                                        Convert.ToUInt16(aCard.Attributes["attack"].Value),
                                        Convert.ToUInt16(aCard.Attributes["defense"].Value),
                                        Convert.ToUInt16(aCard.Attributes["speed"].Value),
                                        aCard.Attributes["image"].Value,
                                        army));

                }

                file.Close();
                return cards;
            }
            catch(System.IO.IOException ioe)
            {
                //wait for the file to be available;
                return null;
            }

            
        }

        public static List<Card> GetRandomCards(Armies army, int cardCount = 15)
        {
            //get all cards then select 15 random cards
            
            //could lead to unbalanced decks
            //can later weight the decks and categorize cards as fighter, Support and Capital class

            List<Card> allArmyCards = ReadArmyCards(army);
            List<Card> returnCards = new List<Card>();
            Random rand = new Random();
            for (int i = 0; i < cardCount; i++)
            {
                int randomCardIndex = rand.Next(allArmyCards.Count);

                returnCards.Add(allArmyCards[randomCardIndex]);
            }
            return returnCards;
        }

        public static Card GetCardByID(Armies army, string pID)
        {
            List<Card> allArmyCards = ReadArmyCards(army);
            foreach (Card i in allArmyCards)
            {
                if (i.Id == pID)
                {
                    return i;
                }

            }

            throw new Exception("Card not found");
        }

    }
}
